package juc.completablefuture;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @ClassName UseCompletableFuture
 * @PackageName completablefuture
 * @projectName myThread
 * @Description 
 * @Author games
 * @Date 2025/8/27 下午1:20
 * @Version 1.0
 */
public class CfAllOf {
    private static ExecutorService executorService = Executors.newFixedThreadPool(5);

    // 生成商品基本信息查询任务的函数


    // 通用的任务生成函数
    public static CompletableFuture<String> createTask(String taskName, long sleepTime, String successMessage) {
        return CompletableFuture.supplyAsync(() -> {
            System.out.println(taskName + ":" + Thread.currentThread().getName());
            try {
                TimeUnit.MILLISECONDS.sleep(sleepTime);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            return successMessage;
        }, executorService);
    }

    public static void main(String[] args) throws Exception {

        // 或者使用通用生成函数
        CompletableFuture<String> cf1 = createTask("T1 查询库存", 100, "库存查询成功");
        CompletableFuture<String> cf2 = createTask("T2 查询物流", 200, "物流查询成功");
        CompletableFuture<String> cf3 = createTask("T3 查询订单", 300, "订单查询成功");
        CompletableFuture<String> cf4 = createTask("T4 查询支付", 400, "支付查询成功");
        CompletableFuture<String> cf5 = createTask("T5 获取优惠券", 500, "优惠券查询成功");
        CompletableFuture<String> cf6 = createTask("T6 获取积分", 600, "积分查询成功");
        CompletableFuture<String> cf7 = createTask("T7 获取会员折扣", 900, "会员折扣查询成功");


        // 等待所有任务完成
        CompletableFuture.allOf(cf1, cf2, cf3, cf4, cf5, cf6, cf7).join();


        // 方法2：使用Stream收集结果
        List<CompletableFuture<String>> futures = Arrays.asList(cf1, cf2, cf3, cf4, cf5, cf6, cf7);
        List<String> results2 = futures.stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList());

        System.out.println("所有任务结果2：");
        results2.forEach(System.out::println);

        executorService.shutdown();
    }
}
